import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthenticationService {

  public authURL = 'http://localhost/api-user/';

  constructor(private httpClient: HttpClient) {
  }

  authenticateUser(data) {
    return this.httpClient.post(`${this.authURL}login`, data);
  }

  registerUser(data) {
    return this.httpClient.post(`${this.authURL}register`, data);
  }

  setBearerToken(token) {
    localStorage.setItem('bearertoken', token);
  }

  getBearerToken() {
    return localStorage.getItem('bearertoken');
  }

  setUserId(userId) {
    localStorage.setItem('userId', userId);
  }

  getUserId() {
    return localStorage.getItem('userId');
  }


  isUserAuthenticated(token): Promise<boolean> {
    return this.httpClient.post<boolean>(`${this.authURL}isAuthenticated`, {'Authorization': `Bearer ${token}`}, {
      headers: new HttpHeaders().set('Authorization', `Bearer ${token}`)
    }).pipe(
       map(res => res['isAuthenticated']
      )
    ).toPromise<boolean>();
  }
}
